// 导入React核心库和必要依赖
import React, { useEffect, useState } from 'react';
// 导入Ant Design组件
import { Button, Modal, Table, Space, Form, Input, Select, message } from 'antd';
import type { TableProps } from 'antd';
import request from '../../../utils/request'; // 封装好的请求工具
import { FormProps } from 'react-router-dom';

// 类型定义 ==================================================
// 表单字段类型定义
type FieldType = {
  shopName?: string;
  shopAddress?: string;
  shopDescription?: string;
  shopScore?: string;
  shopType?: string;
  shopTel?: string;
};

// 表格数据类型定义
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const FileList: React.FC = () => {
  // 状态管理 ================================================
  const [data, setData] = useState<DataType[]>([]); // 表格数据
  const [pageCode, setPageCode] = useState<number>(1); // 当前页码
  const [pageSize, setPageSize] = useState<number>(10); // 每页条数
  const [totalCount, setTotalCount] = useState<number>(0); // 总数据量
  const [searchValue, setSearchValue] = useState<string>(""); // 搜索关键字
  const [isModalOpen, setIsModalOpen] = useState(false); // 控制模态框显示
  const [tit, setTit] = useState(""); // 模态框标题（新增/编辑）
  const [edit, setEdit] = useState(""); // 当前编辑项的ID

  // 表单实例
  const [formAdd] = Form.useForm(); // 新增/编辑表单
  const [searchform] = Form.useForm(); // 搜索表单

  // 数据获取逻辑 ============================================
  const List = async () => {
    await request.get("/list", {
      params: {
        pageCode: pageCode,
        pageSize: pageSize,
        searchValue: searchValue
      }
    }).then(res => {
      setData(res.data.data.data);
      setTotalCount(res.data.data.totalCount);
    });
  };

  // 生命周期钩子 ============================================
  useEffect(() => {
    List();
  }, [pageCode, pageSize, searchValue]); // 当页码、页数或搜索值变化时自动刷新

  // 表格配置 ================================================
  const columns: TableProps<DataType>['columns'] = [
    // 表格列配置
    { title: "Id", dataIndex: "id", key: "id" },
    { title: "商品名字", dataIndex: "shopName", key: "shopName" },
    { title: "商品地址", dataIndex: "shopAddress", key: "shopAddress" },
    { title: "商品描述", dataIndex: "shopDescription", key: "shopDescription" },
    { title: "店家电话", dataIndex: "shopTel", key: "shopTel" },
    { title: "商品分数", dataIndex: "shopScore", key: "shopScore" },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handEdit(record)}>编辑</Button>
          <Button type="primary" onClick={() => handDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 分页处理 ================================================
  const onChange = (pageCode: number, pageSize: number) => {
    setPageCode(pageCode);
    setPageSize(pageSize);
  };

  // 模态框控制 ==============================================
  const showModal = () => {
    setIsModalOpen(true);
    setTit("新增");
    formAdd.resetFields();
  };

  const handleOk = () => {
    setIsModalOpen(false);
    formAdd.submit(); // 触发表单提交
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 编辑操作 ================================================
  const handEdit = (values: DataType) => {
    setIsModalOpen(true);
    setTit("编辑");
    formAdd.setFieldsValue(values); // 表单数据回填
    setEdit(values.id); // 保存编辑项ID
  };

  // 表单提交处理 ============================================
  const onAdd: FormProps<FieldType>['onFinish'] = (values: any) => {
    if (tit === "新增") {
      // 新增请求
      request.put("/list", { ...values }).then(() => {
        message.success("新增成功");
        List(); // 刷新列表
      });
    } else {
      // 编辑请求
      request.post("/list", { ...values, id: edit }).then(() => {
        message.success("编辑成功");
        List(); // 刷新列表
      });
    }
  };

  // 删除操作 ================================================
  const handDelete = (id: string) => {
    request.delete("/list", { params: { id: id } }).then(() => {
      message.success("删除成功");
      List(); // 刷新列表
    });
  };

  // 搜索功能 ================================================
  const onSearch = (values: { searchValue: any }) => {
    setSearchValue(values.searchValue);
    setPageCode(1); // 重置到第一页
  };

  // 页面渲染 ================================================
  return (
    <div>
      {/* 搜索表单 */}
      <Form
        name="basic"
        layout="inline"
        form={searchform}
        onFinish={onSearch}
      >
        <Form.Item label="关键字搜索" name="searchValue">
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item>
          <Button
            onClick={() => {
              searchform.resetFields();
              setSearchValue("");
              setPageCode(1);
            }}
          >
            重置
          </Button>
        </Form.Item>
      </Form>

      {/* 新增按钮 */}
      <Button type="primary" onClick={showModal} style={{ marginBottom: 16 }}>
        新增
      </Button>

      {/* 数据表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{
          total: totalCount,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: onChange,
        }}
      />

      {/* 新增/编辑模态框 */}
      <Modal
        title={tit}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={formAdd} onFinish={onAdd}>
          {/* 商品名称 */}
          <Form.Item
            label="商品名称"
            name="shopName"
            rules={[{ required: true, message: "请输入商品名称" }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

          {/* 商品地址 */}
          <Form.Item
            label="商品地址"
            name="shopAddress"
            rules={[{ required: true, message: "请输入商品地址" }]}
          >
            <Input placeholder="请输入商品地址" />
          </Form.Item>

          {/* 商品描述 */}
          <Form.Item
            label="商品描述"
            name="shopDescription"
            rules={[{ required: true, message: "请输入商品描述" }]}
          >
            <Input placeholder="请输入商品描述" />
          </Form.Item>

          {/* 店家电话（带手机号验证） */}
          <Form.Item
            label="店家电话"
            name="shopTel"
            rules={[{
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入有效的手机号码'
            }]}
          >
            <Input placeholder="请输入11位手机号码" maxLength={11} />
          </Form.Item>

          {/* 商品分数（带范围验证） */}
          <Form.Item
            label="商品分数"
            name="shopScore"
            rules={[{
              required: true,
              validator: (_, value) =>
                value && parseFloat(value) >= 1 && parseFloat(value) <= 5
                  ? Promise.resolve()
                  : Promise.reject('评分必须为1-5之间的数字')
            }]}
          >
            <Input type="number" min={1} max={5} step={0.1} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default FileList;